#include "shfe_md_client.h"
#include <stdio.h>
#include <iostream>
using namespace std;

struct MyEdgeAlign {
    int a;
}__attribute__ ((aligned (64)));

static struct MyEdgeAlign edge1;
static struct ShfeInstInfo *infoPtr;

static inline uint64_t
my_rdtsc() {
    union {
        uint64_t tsc_64;
        struct {
            uint32_t lo_32;
            uint32_t hi_32;
        };
    } tsc;

    asm volatile("rdtscp" :
    "=a" (tsc.lo_32),
        "=d" (tsc.hi_32)
        : : "%ecx");
    return tsc.tsc_64;
}

static inline void 
PrintTick(struct ShfeL5TickData &buf, uint64_t tsc) {
	time_t t = buf.update_time;
	struct tm *m = localtime(&t);
	char outStr[512];
	snprintf(outStr, 512 ,
	"%llu %s %02d:%02d:%02d.%03d %d.%03d %f %d %f %f %f %d %f %d",
					tsc,
					buf.inst_id,
					m->tm_hour, m->tm_min , m->tm_sec, buf.update_milli_sec,
					buf.update_time, buf.update_milli_sec,
					buf.last_px , buf.volume, buf.open_interest , buf.turnover,
					buf.bid_px[0], buf.bid_vol[0], buf.ask_px[0], buf.ask_vol[0] );
	std::cout << outStr << std::endl;
}

#define MAX_INST_NUM 128

int main(int argc, char *argv[]) {	
	char *shm_name = NULL;
	if(argc > 1)
		shm_name = argv[1];

        if(!Raying_ConnectShfeMdShareMem(shm_name , &infoPtr)) {
		cout << "Connect ShareMem Failed" << endl;
		return -1;
	}
	
	struct ShfeInstInfo *infoList = (struct ShfeInstInfo *)infoPtr;
	int max_subs_idx = 0;
	for(int i = 0 ; i < MAX_INST_NUM; i ++) {
		if(infoList[i].subs_index > max_subs_idx)
			max_subs_idx = infoList[i].subs_index;
		
		if(infoList[i].inst_id[0] != 0) {
			struct ShfeInstInfo *data = infoList + i;
			printf("subs succ %s %d %f %f %d %f %f %f\n" ,
                        data->inst_id, data->subs_index,  data->codec_price , data->price_tick , data->volume_multiple ,
                        data->strike_price, data->upper_price, data->lower_price );
		}
	}

	int subs_num = max_subs_idx + 1;
	cout << "Subs " << subs_num << " Instruments" << endl;	

	 struct InflateL5TickData *currItem;

	uint64_t lastBatchTsc[MAX_INST_NUM] = {0};	
	struct InflateL5TickData lastBatchHq[MAX_INST_NUM];
	uint64_t lastOutTsc = 0;
	
    while(1) {
        if( Raying_GetShfeMktData(&currItem)) {	
          //  PrintTick(currItem , 0);	
             cout << currItem->volume <<endl;
        } 	        
    }		

	cout << "Exit Program " << endl;
	return 0;
}
